package com.sunnada.edu.system.pub.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;

import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;


public class FileTools {
	/**
	 * explain 复制文件到指定文件夹中
	 * 
	 * @author chs 2015-2-11 update chs 2015-2-11
	 * @param from
	 * @param to
	 * @param newName
	 *            新名称
	 */
	public static void copyFile(File from, File to, String newName) {
		InputStream in = null;
		FileOutputStream out = null;
		try {
			if (to.exists() == false) {
				to.mkdir();
			}
			if(from.exists()==true){
				in = new FileInputStream(from);
				out = new FileOutputStream(to + "/" + newName);
				byte[] buffer = new byte[8192];
				int ins;
				while ((ins = in.read(buffer)) != -1) {
					out.write(buffer, 0, ins);
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(in!=null){
					in.close();
				}				
				if(out!=null){
					out.flush();
					out.close();
				}				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**经测试，发现以下方法比copyFile运行效率更低，更慢，可以找个时间研究下*/
	   public void fileChannelCopy(File s, File t) {
	        FileInputStream fi = null;
	        FileOutputStream fo = null;
	        FileChannel in = null;
	        FileChannel out = null;
	        try {
	            fi = new FileInputStream(s);
	            fo = new FileOutputStream(t);
	            in = fi.getChannel();
	            out = fo.getChannel();
	            in.transferTo(0, in.size(), out);
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	            	if(fi!=null){
	            		fi.close();
	            	}
	                if(in!=null){
	                	in.close();
	                }
	                if(fo!=null){
	                	fo.close();
	                }
	                if(out!=null){
	                	out.close();
	                }	                
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }

	/***
	 * explain 压缩多个文件 
	 * @author chs 2015-2-13
	 * update chs 2015-2-13
	 * @param files
	 * @param FilePath
	 * @return String
	 */
	public static String zip(File[] files, String FilePath) {
		byte[] buffer = new byte[8192];
		String strZipPath = FilePath;
		FileInputStream fis = null;
		ZipOutputStream out = null;
		try {
			 out= new ZipOutputStream(new FileOutputStream(
					strZipPath));
			for (int i = 0; i < files.length; i++) {
				File tFile = files[i];
				fis = new FileInputStream(tFile);
				out.putNextEntry(new ZipEntry(tFile.getName()));
				out.setEncoding("GBK");
				int len;
				while ((len = fis.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fis!=null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public static void fileDelete(String path) {
		File file = new File(path);
		if (file.isDirectory()) {
			File[] ff = file.listFiles();
			for (int i = 0; i < ff.length; i++) {
				fileDelete(ff[i].getPath());
			}
		}
		if(file.exists())
		file.delete();
	}
	/**
	 * explain 生成文本
	 * @author chs 2015-2-13
	 * update chs 2015-2-13
	 * @param path
	 * @param content void
	 */
	public static void createTxt(String path, String content) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				f.createNewFile();
			}
			FileWriter fw = new FileWriter(f);
			PrintWriter pw = new PrintWriter(fw);
			pw.append(content);
			pw.flush();
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	 public void zip(String fromPath,String toPath)  {
	        String zipFileName = toPath; //打包后文件名字
	        try {
				zip(zipFileName, new File(fromPath));
			} catch (Exception e) {
				e.printStackTrace();
			}
	    }

	    private void zip(String zipFileName, File inputFile) {
	        ZipOutputStream out = null;
			try {
				out = new ZipOutputStream(new FileOutputStream(zipFileName));
				zip(out, inputFile, "");			   
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}finally{
				if(out!=null){ 
					 try { 
						out.close(); 
					} catch (IOException e) { 
						e.printStackTrace(); 
					}
				}
			}
	       
	    }

	    private void zip(ZipOutputStream out, File f, String base)  {
	        if (f.isDirectory()) {
		           File[] fl = f.listFiles();
		           try {
					out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
					 base = base.length() == 0 ? "" : base + "/";
			           for (int i = 0; i < fl.length; i++) {
			           zip(out, fl[i], base + fl[i].getName());
			           }
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }else {
	        	FileInputStream in = null;
	           try {
				   out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
				   in = new FileInputStream(f);
		           int b;
		           //System.out.println(base);
		           while ( (b = in.read()) != -1) {
		            out.write(b);
		         }
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					if(in!=null){
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					
				}
	          
	         
	       }
	    }
	    /**
	     * explain 下载文件 
	     * @author chs 2015-4-23
	     * update chs 2015-4-23
	     * @param response
	     * @param file
	     * @param excelName void
	     */
	    public static void outputFile(HttpServletResponse response, File file,
				String excelName) {
			FileInputStream fs = null;
			 PrintWriter out = null;
			    try {	           
			    	response.reset();
					response.setContentType("application/octet-stream");
					response.setHeader("Content-Disposition", "attachment;fileName=" 
										+ new String(excelName.getBytes("gb2312"),"iso-8859-1"));
					response.addHeader("Content-Length", "" + file.length());
			        fs = new FileInputStream(file);
			        int b = 0;
			        out = response.getWriter();
			        while ((b = fs.read()) != -1) {
			            out.write(b);
			        }    	           
			    } catch (Exception e) {
			        e.getStackTrace();
			    }finally{
			    	if(out!=null){
			    		out.flush();
			    		out.close();
			    	}
			    	if(fs!=null){
			    		try {
							fs.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
			    	}
			    }
		}	
	    
	    public static void main(String [] temp){
	        FileTools book = new FileTools();
	        /*try {
	           book.zip("c:\\tt","c:\\a.zip");//你要压缩的文件夹
	        }catch (Exception ex) {
	           ex.printStackTrace();
	       }*/
	   /*    long s = System.currentTimeMillis();
	        File f = new File("f:\\ecard-dev.zip");
	        File t = new File("c:\\ecard-dev1.zip");
	        book.fileChannelCopy(f, t);
	        long e = System.currentTimeMillis();
	        System.out.println(e-s);*/
	        
	        
	        long s = System.currentTimeMillis();
	        File f = new File("f:\\ecard-dev.zip");
	        File t = new File("c:\\");
	        book.copyFile(f,t,"ecard-dev1.zip");
	        long e = System.currentTimeMillis();
	        System.out.println(e-s);
	       
	        
	    }
	    
	    
}
